package com.wei.czz.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wyw
 * date: 2025-05-13 09:41:45
 * className: ValidationUtils jsr303校验工具类
 * version: 1.0
 * description:
 */
public class ValidationUtils {

    private static final Logger log = LoggerFactory.getLogger(ValidationUtils.class);

    /**
     * jsr303校验器
     */
    private static final Validator validator;

    static {
        // 初始化校验器
        try (ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory()) {
            validator = validatorFactory.getValidator();
        }
    }

    /**
     * 校验对象
     * @param t   参数对象
     * @param <T> 泛型
     * @return 错误提示
     */
    public static <T> String valid(T t) {
        // 校验对象
        Set<ConstraintViolation<T>> violationSet = validate(t);
        // 获取错误提示
        return getErrorMessage(violationSet, false);
    }

    /**
     * 校验对象
     * @param t   参数对象
     * @param <T> 泛型
     * @return 错误提示
     */
    public static <T> String simpleValid(T t) {
        // 校验对象
        Set<ConstraintViolation<T>> violationSet = validate(t);
        // 获取错误提示
        return getErrorMessage(violationSet, true);
    }

    /**
     * 校验对象
     * @param t   参数对象
     * @param <T> 泛型
     * @return 校验结果
     */
    public static <T> Set<ConstraintViolation<T>> validate(T t) {
        Set<ConstraintViolation<T>> violationSet = validator.validate(t);
        log.info("jsr303校验结果：class.name={} {}", t.getClass().getName(), violationSet);
        return violationSet;
    }

    /**
     * 获取错误提示
     * @param validate 字段校验错误信息集合
     * @return 错误提示
     */
    private static <T> String getErrorMessage(Set<ConstraintViolation<T>> validate, boolean first) {
        if (CollectionUtils.isEmpty(validate)) {
            // 错误字段集合为空，校验通过
            return StringUtils.EMPTY;
        }
        if (first) {
            // 只获取第一个错误信息
            return validate.iterator().next().getMessage();
        }
        StringBuilder sb = new StringBuilder();
        for (ConstraintViolation<T> constraintViolation : validate) {
            // 拼接错误提示
            sb.append(constraintViolation.getMessage()).append(";");
        }
        return sb.toString();
    }
}
